/*S4WjJncwqf0Ks4LzLMbXC9mI5FG9WuP92NqmRnpjQbBJ3VkjivlCsBiLvHBSIYm2*/
import React, { Component } from 'react';
import echarts from 'echarts';
import { skipClick, toggleShow, changeTime } from '../events';
import constant from '../../constants';
import { ajax, toast, formatDatetime } from 'nc-lightapp-front';
import ampub from 'ampub';

const { utils } = ampub;
const { multiLangUtils, getThemeUtils } = utils;
const { getMultiLangByID } = multiLangUtils;

/*
 盘点结果页面
 liuzjk
*/
const BILL_STATUS = {
    UNCOMMIT: {
        display: getMultiLangByID('statusUtils-000000') /* 自由态*/,
        value: '0'
    },
    COMMIT: {
        display: getMultiLangByID('statusUtils-000001') /* 已提交*/,
        value: '1'
    },
    APPROVE_ING: {
        display: getMultiLangByID('statusUtils-000002') /* 审批中*/,
        value: '2'
    },
    APPROVE: {
        display: getMultiLangByID('statusUtils-000003') /* 审批通过*/,
        value: '3'
    },
    UNAPPROVE: {
        display: getMultiLangByID('statusUtils-000004') /* 审批未通过*/,
        value: '4'
    },
    CLOSE: {
        display: getMultiLangByID('statusUtils-000004') /* 关闭*/,
        value: '6'
    }
};
export default class InventoryResult extends Component {

    constructor(props) {
        super(props);
        this.option = {};
        this.optionLine = {};
        this.myChart = '';
        this.myChartLine = '';
    }

    UNSAFE_componentWillReceiveProps(nextProps) {
        this.setEchartsData(nextProps);
    }

    componentDidMount() {
        const blackColor = '#d9d9d9';
        // 绘制echars页面
        this.option = {
            title: {
                x: 'left',
                align: 'right',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'normal',
                    color: getThemeUtils() == 'black' ? blackColor : '#333'
                }
            },
            series: [
                {
                    name: getMultiLangByID('201203004A-000000') /* 访问来源*/,
                    type: 'pie',
                    radius: ['45%', '55%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            show: true,
                            position: 'center',
                            formatter: '',
                            color: '#ccc',
                            fontSize: 18
                        }
                    },
                    data: [] // values
                }
            ],
            color: ['#20CBAF', ' #2ec25b', ' #facc14', '#ef4864', '#3000ff']
        };
        this.optionLine = {
            // 数据区域放缩
            dataZoom: [
                {
                    show: true,
                    realtime: true,
                    filterMode: 'filter',
                    start: 0,
                    end: 100
                }
            ],
            // 悬浮提示框
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                },
                formatter: function(params) {
                    const xAxis = params[0].name;
                    const nameArr = params.map(({ seriesName }) => seriesName);
                    const dataArr = params.map(({ data }) => data);
                    let totalNum = 0;
                    for (let i = 0; i < dataArr.length; i++) {
                        totalNum += dataArr[i].value * 1;
                    }
                    let str = '';
                    for (let i = 0; i < nameArr.length; i++) {
                        str += `<p>${nameArr[i]}：<span>${dataArr[i].value}</span></p >`;
                    }
                    const content = getMultiLangByID('201203004A-000001', { totalNum }); /* 共分配{totalNum}个资产*/
                    return `<div class="toolTip">
                        <p>${xAxis} <span>${content}</span></p >
                        ${str}
                        </div>`;
                }
            },
            legend: {
                data: [
                    {
                        name: getMultiLangByID('201203004A-000004') /* 未盘*/,
                        textStyle: { color: getThemeUtils() == 'black' ? blackColor : '#333' }
                    },
                    {
                        name: getMultiLangByID('201203004A-000003') /* 已盘*/,
                        textStyle: { color: getThemeUtils() == 'black' ? blackColor : '#333' }
                    }
                ],
                left: 'center'
            },
            xAxis: {
                type: 'category',
                data: [], // x_axis,
                axisLine: { lineStyle: { color: getThemeUtils() == 'black' ? blackColor : '#333' } }
            },
            yAxis: {
                type: 'value',
                minInterval: 1,
                axisLine: {
                    // 坐标轴是否显示
                    show: true,
                    lineStyle: { color: getThemeUtils() == 'black' ? blackColor : '#333' }
                },
                splitLine: {
                    show: true,
                    lineStyle: { color: { color: getThemeUtils() == 'black' ? '#39393f' : '#333' } }
                }
            },
            series: [
                {
                    name: getMultiLangByID('201203004A-000004') /* 未盘*/,
                    type: 'bar',
                    stack: getMultiLangByID('201203004A-000005') /* 总量*/,
                    barWidth: 15,
                    itemStyle: {
                        normal: {
                            color: function(params) {
                                // 控制柱状图的颜色
                                const colorList = ['#20CBAF', '#20CBAF', '#20CBAF', '#20CBAF', '#20CBAF'];
                                return colorList[params.dataIndex];
                            }
                        }
                    },
                    data: [] // unfinished
                },
                {
                    name: getMultiLangByID('201203004A-000003') /* 已盘*/,
                    type: 'bar',
                    stack: getMultiLangByID('201203004A-000005') /* 总量*/,
                    barWidth: 15,
                    itemStyle: {
                        normal: {
                            color: function(params) {
                                const colorList = ['#FF9A48', '#FF9A48', '#FF9A48', '#FF9A48'];
                                return colorList[params.dataIndex];
                            }
                        }
                    },
                    data: [] // finished
                }
            ],
            color: ['#20CBAF', '#FF9A48']
        };
        this.myChart = echarts.init(document.getElementById('echartPieBox'));
        this.myChartLine = echarts.init(document.getElementById('echartsLineBox'));
        this.myChart.setOption(this.option);
        this.myChartLine.setOption(this.optionLine);
        // 当浏览器窗口发生变化时候，echarts大小随着变化
        window.addEventListener('resize', () => {
            this.myChart.resize();
            this.myChartLine.resize();
        });
        this.setEchartsData(this.props);
        // 点击事件 -- 点击柱状图的未分配人员
        const { that } = this.props;
        this.myChartLine.on('click', (context) => {
            if (context.name == getMultiLangByID('201203004A-000006') /* 未分配人员*/) {
                const print_param = {
                    type: '2', // 打印类型：0.按照盘点结果进行筛选的打印（默认）、1.按照盘点人对盘点明细筛选的打印、2.未分配盘点人列表的打印
                    inventory_checkuser: '', // 计划盘点人的Pk值，默认为空
                    check_result: 'all' // 盘点结果的值：0.相符、1.盘盈、2.盘亏、3.不符，默认为0
                };
                ajax({
                    url: constant.URL.QUERY_NOINVENCHECKUSER,
                    data: { pk: that.state.pk_inventory },
                    success: (res) => {
                        that.childformData.head = res.data.head.card_head.rows;
                        that.childformData.body = res.data.body.anewAllot.rows;
                        that.setState({ current: 7, inventoryStatus: 'confirmedAllot', print_param }, () => {
                            toggleShow(that, that.props);
                            this.props.cardTable.setTableData(
                                constant.AREA.STEP.ANEWALLOT,
                                res.data.body.anewAllot,
                                false
                            );
                            this.props.cardTable.setStatus(constant.AREA.STEP.ANEWALLOT, 'edit');
                        });
                    },
                    error: (res) => {
                        if (res && res.message) {
                            toast({ content: res.message, color: 'danger' });
                        }
                    }
                });
            } else {
                // 点击已分配盘点人，进入盘点明细页面
                const pk_inventory = that.state.pk_inventory;
                const current = 6;
                let inventoryStatus = 'confirmed';
                if (that.state.bill_status != '0' && that.state.bill_status != '4') {
                    inventoryStatus = 'browse';
                }
                const { cardTable } = that.props;
                const queryInfo = {};
                const tempUserdefObj = {
                    pk_inventory,
                    check_user_pk: context.data.id
                };
                queryInfo.userdefObj = tempUserdefObj;
                const print_param = {
                    type: '1', // 打印类型：0.按照盘点结果进行筛选的打印（默认）、1.按照盘点人对盘点明细筛选的打印、2.未分配盘点人列表的打印
                    inventory_checkuser: tempUserdefObj.check_user_pk, // 计划盘点人的Pk值，默认为空
                    check_result: 'all' // 盘点结果的值：0.相符、1.盘盈、2.盘亏、3.不符，默认为0
                };
                cardTable.closeExpandedRow(constant.AREA.STEP.DETAIL_LIST);
                ajax({
                    url: constant.URL.QUERY_BYINVENCHECKUSER,
                    data: queryInfo,
                    success: (res) => {
                        if (res.data.head != null) {
                            that.echartsData.pk_org
								= res.data.head[constant.AREA.CARD.BODY_HEAD].rows[0].values.pk_org.value;
                            that.childformData.head = res.data.head[constant.AREA.CARD.BODY_HEAD].rows;
                        }
                        if (res.data.body != null) {
                            that.setState({ current, inventoryStatus, print_param }, () => {
                                toggleShow(that, that.props);
                            });
                            setTimeout(() => {
                                cardTable.setTableData(
                                    constant.AREA.STEP.DETAIL_LIST,
                                    res.data.body.anewAllot,
                                    null,
                                    true,
                                    true
                                );
                                cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
                            }, 0);
                        } else {
                            that.setState({ current, inventoryStatus, print_param }, () => {
                                toggleShow(that, that.props);
                            });
                            setTimeout(() => {
                                cardTable.setTableData(constant.AREA.STEP.DETAIL_LIST, { rows: [] });
                                cardTable.setStatus(constant.AREA.STEP.DETAIL_LIST, 'browse');
                            }, 0);
                        }
                    },
                    error: (res) => {
                        if (res && res.message) {
                            toast({ content: res.message, color: 'danger' });
                        }
                    }
                });
            }
        });
    }

    // 设置echars图表数据
    setEchartsData = (nextProps) => {
        const { echartsData } = nextProps;
        const { total_num, bar_data, pie_data } = echartsData;
        const { x_axis, unfinished, finished } = bar_data;
        const { values } = pie_data;
        const formatterTemp = getMultiLangByID('201203004A-000007', { total_num }); /* 总共{total_num}个资产*/
        // 从传过来的值中获取环状图的值
        const pie_value = [];
        values.forEach((item, index) => {
            if (index < 5) {
                pie_value.push(item.value);
            }
        });
        // 总数
        this.option.series[0].label.normal.formatter = formatterTemp;
        // 环状图数据
        this.option.series[0].data = pie_value;
        // X轴数据
        this.optionLine.xAxis.data = x_axis;
        // 未盘数据
        this.optionLine.series[0].data = unfinished;
        // 已盘数据
        this.optionLine.series[1].data = finished;
        this.myChart.setOption(this.option);
        this.myChartLine.setOption(this.optionLine);
    };

    render() {
        const { that } = this.props;
        const legendName = constant.LEGEND_NAME;
        let { start_date, end_date, check_range, bill_code, bill_status } = that.childformData.head;
        let temp_start_date = '';
        let temp_end_date = '';
        start_date != null && (temp_start_date = changeTime(start_date));
        end_date != null ? (temp_end_date = changeTime(end_date)) : (temp_end_date = '');
        /* 穿透列表数据 */
        const data = this.props.echartsData.pie_data.values ? this.props.echartsData.pie_data.values : '';
        bill_status = bill_status && (typeof bill_status === 'string' ? bill_status : bill_status.value);
        bill_code = bill_code && (typeof bill_code === 'string' ? bill_code : bill_code.value);
        const temp_bill_status
			= bill_status == 0
			    ? BILL_STATUS.UNCOMMIT.display
			    : bill_status == 1
			        ? BILL_STATUS.COMMIT.display
			        : bill_status == 2
			            ? BILL_STATUS.APPROVE_ING.display
			            : bill_status == 3
			                ? BILL_STATUS.APPROVE.display
			                : bill_status == 4 ? BILL_STATUS.UNAPPROVE.display : BILL_STATUS.UNCOMMIT.display;

        return (
            <div className="result-area nc-theme-area-bgc">
                <div className="msg-area">
                    <div>
                        <p className="nc-theme-title-font-c">
                            {`${getMultiLangByID('201203004A-000008') /* 单据号*/}:`}
                            <span>{bill_code}</span>
                        </p>
                        <p className="nc-theme-title-font-c">
                            {`${getMultiLangByID('201203004A-000009') /* 单据状态：*/}:`}
                            <span>{temp_bill_status}</span>
                        </p>
                    </div>
                </div>
                <div className="pie-box">
                    <div id="echartPieBox" />
                    <div className="legend-area">
                        {legendName.map((item, index) => (
                            // 给穿透列表赋值并添加点击事件
                            <p
                                key={index}
                                className={`legend-${index * 1 + 1}`}
                                onClick={() => {
                                    skipClick.call(this, index, that);
                                }}
                                fieldid={`${index}legend_btn`}
                            >
                                {getMultiLangByID(item)
                                    /* '201203004A-000004' 未盘,
										 * '201203004A-000036' 相符,
										 * '201203004A-000037' 不符,
										 * '201203004A-000038' 盘盈,
										 * '201203004A-000039' 盘亏,
										 * '201203004A-000040' 全部,
										 * '201203004A-000051' 不符+盘盈+盘亏 */
                                }
                                <span>{data.length == 0 ? '' : getMultiLangByID(data[index].value)}</span>
                            </p>
                        ))}
                    </div>
                    <div className="assetInfo">
                        <p>
                            <span className="title">{`${getMultiLangByID('201203004A-000010') /* 盘点时间*/}:`}</span>
                            <span>
                                {getMultiLangByID('201203004A-000011')
									+ /* 从*/ formatDatetime(temp_start_date, 'date')}{' '}
                            </span>
                            <span>
                                {getMultiLangByID('201203004A-000012') /* 至*/ + formatDatetime(temp_end_date, 'date')}
                            </span>
                        </p>
                        <p>
                            {check_range ? (
                                <div>
                                    <p>{`${getMultiLangByID('201203004A-000013') /* 盘点范围*/}:`}</p>
                                    <div>
                                        <span>{check_range}</span>
                                    </div>
                                </div>
                            ) : (
                                ''
                            )}
                        </p>
                    </div>
                </div>
                <div id="echartsLineBox" />
            </div>
        );
    }

}

/*S4WjJncwqf0Ks4LzLMbXC9mI5FG9WuP92NqmRnpjQbBJ3VkjivlCsBiLvHBSIYm2*/